package com.example.springbootshiro.exception;

import com.alibaba.fastjson.JSON;
import com.example.springbootshiro.response.BusinessError;
import com.example.springbootshiro.response.CommonReturnData;
import com.example.springbootshiro.response.GlobalCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

/**
 * 统一异常管理:
 * <p>
 * 结合方法型注解@ExceptionHandler，
 * 用于捕获Controller中抛出的指定类型的异常，从而达到不同类型的异常区别处理的目的；
 * <p>
 * Created by YangGang on 2019/03/24 17:15。
 */
@Slf4j
@ControllerAdvice
public class ExceptionAdvice {
    /**
     * 最外层异常Exception捕捉
     *
     * @param exception
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        log.error("[[系统异常]]" + exception.getMessage(), exception);
        log.error("[请求路径]" + request.getRequestURI());
        log.error("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        return CommonReturnData.error(exception.getMessage());
    }

    /**
     * 业务异常捕捉（用户“主动”抛出的异常）
     *
     * @param exception
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(BusinessError.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(BusinessError exception, HttpServletRequest request, HttpServletResponse response) {
        log.warn("[业务异常]" + exception.getMessage());
        log.warn("[请求路径]" + request.getRequestURI().toString());
        log.warn("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        return CommonReturnData.error(exception);
    }

    /**
     * 上传文件过大时异常捕捉
     *
     * @param exception
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(MaxUploadSizeExceededException exception, HttpServletRequest request, HttpServletResponse response) {
        log.warn("[上传文件过大异常]", exception.getMessage());
        log.warn("[请求路径]" + request.getRequestURI().toString());
        log.warn("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        return CommonReturnData.error("上传文件过大");
    }

    /**
     * hibernate-validator 进行校验参数时出现的异常捕捉
     *
     * @param exception
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(BindException exception, HttpServletRequest request, HttpServletResponse response) {
        log.warn("[参数校验时异常1]" + exception.getMessage());
        log.warn("[请求路径]" + request.getRequestURI().toString());
        log.warn("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        BindingResult bindingResult = exception.getBindingResult();
        String message = bindingResult.getFieldError().getDefaultMessage();
        return CommonReturnData.create(null, GlobalCodeEnum.PARAMS_INVALID.getCode(), message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(MethodArgumentNotValidException exception, HttpServletRequest request, HttpServletResponse response) {
        log.warn("[参数校验时异常2]" + exception.getMessage());
        log.warn("[请求路径]" + request.getRequestURI().toString());
        log.warn("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        BindingResult bindingResult = exception.getBindingResult();
        String message = bindingResult.getFieldError().getDefaultMessage();
        return CommonReturnData.create(null, GlobalCodeEnum.PARAMS_INVALID.getCode(), message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(ConstraintViolationException exception, HttpServletRequest request, HttpServletResponse response) {
        log.warn("[参数校验时异常3]" + exception.getMessage());
        log.warn("[请求路径]" + request.getRequestURI().toString());
        log.warn("[请求参数]" + JSON.toJSONString(request.getParameterMap()));
        String message = exception.getConstraintViolations().iterator().next().getMessage();
        return CommonReturnData.create(null, GlobalCodeEnum.PARAMS_INVALID.getCode(), message);
    }

}
